package cn.com.zsw.gblog.config.security;

import cn.com.zsw.gblog.modules.gblog.enums.ResponseCode;
import cn.com.zsw.gblog.utils.ServletUtils;
import cn.com.zsw.gblog.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author ：shiwangzhou
 * @Date ：Created in 2020-09-15 22:05
 * @Description：
 */
@Slf4j
@Component
public class AdminAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException {

        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            log.error(e.getMessage());
        } else if (e instanceof LockedException) {
            log.error("账户被锁定，请联系管理员!");
        } else if (e instanceof CredentialsExpiredException) {
            log.error("证书过期，请联系管理员!");
        } else if (e instanceof AccountExpiredException) {
            log.error("账户过期，请联系管理员!");
        } else if (e instanceof DisabledException) {
            log.error("账户被禁用，请联系管理员!");
        } else {
            log.error("登录失败：", e);
        }
        R r = R.status(ResponseCode.ERROR.getCode()).msg(e.getMessage());
        ServletUtils.output(response, r);
    }

}